from django.shortcuts import render, redirect, HttpResponse, reverse
from django.http.response import JsonResponse
from web import models
from utils.tencent.cos import delete_bucket

'''配置'''


def setting(request, project_id):
    return render(request, 'setting.html')


def setting_delete(request, project_id):
    if request.method == 'GET':
        return render(request, 'setting_delete.html')
    # 校验
    project_name = request.POST.get('project_name')
    if project_name:
        # 当前要删除的项目对象
        project_obj = models.Project.objects.filter(name=project_name, id=project_id).first()
        if project_obj:
            # 只能创建者才能删除项目
            if project_obj.creator.username == request.tracer.user.username:
                # cos删除调用接口
                project_obj.delete()
                delete_bucket(bucket=request.tracer.project.bucket, region=request.tracer.project.region)
                url = reverse('setting_delete', kwargs={'project_id': project_id})
                return redirect(url)
            # 数据库删除
            else:

                return render(request, 'setting_delete.html', {'error': '您不是当前项目的创建者，无法进行删除操作'})
        else:
            return render(request, 'setting_delete.html', {'error': '该项目不存在'})
    else:
        return render(request, 'setting_delete.html', {'error': '项目名称不能为空'})
